

import { Card,  Form, Button, DatePicker, Breadcrumb, Radio, Select,
    Table, Tag, Space, Popconfirm
} from 'antd'

//在需要改的js文件里引入
import locale from 'antd/es/date-picker/locale/zh_CN';
import 'dayjs/locale/zh-cn';

import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import img404 from '@/assets/error.png'
import './index.scss'
import { useEffect, useState } from 'react';
import { useStore } from '@/store';
import { observer } from 'mobx-react-lite'
import { http } from '@/utils';
import { useNavigate } from 'react-router-dom'



const { RangePicker } = DatePicker


const Article = () => {
    const navigate = useNavigate()
/**
 * store管理的数据
 */
    const { channelStore } = useStore();

/**
 * 文章列表数据
 */
    //文章列表数据管理
    const [articleData, setArticleData] = useState({
        list: [],
        count: 0
    })
    const columns = [
        {
          title: '封面',
          dataIndex: 'cover',
          width:120,
          render: cover => {
            return <img src={cover.images[0] || img404} width={80} height={60} alt="" />
          }
        },
        {
          title: '标题',
          dataIndex: 'title',
          width: 220
        },
        {
          title: '状态',
          dataIndex: 'status',
          render: data => formatStatus(data)
        },
        {
          title: '发布时间',
          dataIndex: 'pubdate'
        },
        {
          title: '阅读数',
          dataIndex: 'read_count'
        },
        {
          title: '评论数',
          dataIndex: 'comment_count'
        },
        {
          title: '点赞数',
          dataIndex: 'like_count'
        },
        {
          title: '操作',
          render: data => {
            return (
              <Space size="middle">
                <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={() => handleEdit(data)} />
                <Popconfirm title="确认删除该条文章吗?" okText="确认" cancelText="取消" onConfirm={() => handleDelete(data)}>
                    <Button
                    type="primary"
                    danger
                    shape="circle"
                    icon={<DeleteOutlined />}
                    />
                </Popconfirm>
              </Space>
            )
          }
        }
    ]
    //参数管理
    const [params, setParams] = useState({
        page: 1,
        per_page: 20
    })

/**
 * 频道类型
 */
    const fieldNames = {
        label: 'name', // 自定义 label 字段名
        value: 'id', // 自定义 value 字段名
    };
    

/**
 * 发送接口请求
 */
    useEffect(()=>{
        async function getArticleList(){
            const res = await http.get('/mp/articles', {params});
            const { results, total_count } = res.data;
            setArticleData({
                list: results,
                count: total_count,
            })
        }
        getArticleList();   //获取文章列表
    },[params])


    //点击筛选
    const onSearch = (values)=>{
        const {status,channel_id,date}=values;
        //格式化表单数据
        const _params = {};
        _params.status = status;
        if(channel_id){
            _params.channel_id = channel_id;
        }
        if(date){
            _params.begin_pubdate = date[0].format('YYYY-MM-DD');
            _params.ded_pubdate = date[1].format('YYYY-MM-DD')
        }
        //修改params参数，触发接口再次发起
        setParams({
            ...params,
            ..._params
        })
    }
    //删除操作
    const handleDelete = async(data)=>{
        console.log('data-->',data)
        await http.delete(`mp/articles/${data.id}`);
        setParams({
            ...params,
            page: 1,
            per_page: 20,
        })
    }
    // 编辑操作
    const handleEdit = (data)=>{
        console.log('handleEdit==>',data)
        navigate(`/layout/publish?id=${data.id}`)
    }
    //页数改变事件
    const pageChange =(page, pageSize)=>{
        setParams({
            ...params,
            page: page,
            per_page: pageSize
        })
    }

  const formatStatus = (type) => {
    const TYPES = {
      0: <Tag color="pink">草稿</Tag>,
      1: <Tag color="orange">待审核</Tag>,
      2: <Tag color="green">审核成功</Tag>,
      3: <Tag color="red">审核失败</Tag>,
    }
    return TYPES[type]
  }

    return <div>
        <Card >    
            <Breadcrumb
                separator=">"
                items={[
                    {
                        title: '首页',
                        href: '/home',
                    },
                    {
                        title: '内容管理',
                        href: '/home',
                    }
                ]}
                style={{ marginBottom: 20 }}
            />

            

            <Form onFinish={ onSearch } initialValues={{ status: undefined}}>
                <Form.Item label="状态" name="status">
                    <Radio.Group>
                        <Radio value={undefined}>全部</Radio>
                        <Radio value={0}>草稿</Radio>
                        <Radio value={1}>待审核</Radio>
                        <Radio value={2}>审核通过</Radio>
                        <Radio value={3}>审核失败</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item label="频道" name="channel_id">
                    <Select
                    placeholder="请选择文章频道"
                    style={{ width: 160 }}
                    fieldNames={fieldNames}
                    options={channelStore.channelList}
                    />
                </Form.Item>

                <Form.Item label="日期" name="date">
                    <RangePicker locale={locale}></RangePicker>
                </Form.Item>

                <Form.Item>
                    <Button type="primary" htmlType="submit" style={{ marginLeft: 80 }}>
                        筛选
                    </Button>
                </Form.Item>
            </Form>
        </Card>
        
        <Card title={`根据筛选条件共查询到 ${articleData.count}条结果：`}>
            <Table rowKey="id" columns={columns} dataSource={articleData.list}
                pagination={{
                    total: articleData.count,
                    pageSize: params.per_page,
                    current: params.page,
                    onChange: pageChange
                }}
            />
        </Card>
    </div>
}
export default observer(Article)